using B.S.NewMedical.Api.Read.Application.Command.Department;
using B.S.NewMedical.Api.Read.DTOS.Department;
using B.S.NewMedical.Domain.Doctor;
using B.S.NewMedical.ErrorCode;
using B.S.NewMedical.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.NewMedical.Api.Read.Application.Handler.Department
{
    /// <summary>
    /// 获取科室列表处理器
    /// 处理获取科室列表的业务逻辑，支持分页和搜索
    /// </summary>
    public class GetDepartmentListHandler : IRequestHandler<GetDepartmentListCommand, ApiResult<DepartmentListDto>>
    {
        private readonly IBaseRepository<DepartmentModel> _departmentRepository;
        private readonly ILogger<GetDepartmentListHandler> _logger;

        /// <summary>
        /// 构造函数
        /// 注入依赖的服务
        /// </summary>
        /// <param name="departmentRepository">科室仓储接口</param>
        /// <param name="logger">日志记录器</param>
        public GetDepartmentListHandler(IBaseRepository<DepartmentModel> departmentRepository, ILogger<GetDepartmentListHandler> logger)
        {
            _departmentRepository = departmentRepository;
            _logger = logger;
        }

        /// <summary>
        /// 处理获取科室列表命令
        /// 执行获取树形结构科室列表的业务逻辑
        /// </summary>
        /// <param name="request">获取科室列表命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>树形结构的科室列表</returns>
        public async Task<ApiResult<DepartmentListDto>> Handle(GetDepartmentListCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始处理获取树形科室列表命令");

                // 获取所有未删除的科室
                var allDepartments = _departmentRepository.GetAll()
                    .Where(d => !d.IsDeleted)
                    .OrderBy(d => d.Id)
                    .ToList();

                // 构建树形结构
                var treeDepartments = BuildDepartmentTree(allDepartments);

                // 构建返回结果
                var result = new DepartmentListDto
                {
                    Departments = treeDepartments,
                    TotalCount = allDepartments.Count
                };

                _logger.LogInformation("获取树形科室列表成功，总记录数: {TotalCount}, 顶级科室数: {TopLevelCount}", 
                    allDepartments.Count, treeDepartments.Count);

                return new ApiResult<DepartmentListDto>
                {
                    Code = ApiEnum.Success,
                    Msg = "获取树形科室列表成功",
                    Data = result
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取树形科室列表时发生异常");
                return new ApiResult<DepartmentListDto>
                {
                    Code = ApiEnum.Error,
                    Msg = $"获取树形科室列表失败: {ex.Message}"
                };
            }
        }

        /// <summary>
        /// 构建科室树形结构
        /// </summary>
        /// <param name="allDepartments">所有科室列表</param>
        /// <returns>树形结构的科室列表</returns>
        private List<DepartmentTreeDto> BuildDepartmentTree(List<DepartmentModel> allDepartments)
        {
            var departmentDict = allDepartments.ToDictionary(d => d.Id);
            var treeDepartments = new List<DepartmentTreeDto>();

            foreach (var dept in allDepartments)
            {
                var treeNode = new DepartmentTreeDto
                {
                    Id = dept.Id,
                    DepartmentName = dept.DepartmentName,
                    DepartmentAddr = dept.DepartmentAddr,
                    RegistrationFee = dept.RegistrationFee,
                    Type = dept.Type,
                    IsOnline = dept.IsOnline,
                    IsEmergencyService = dept.IsEmergencyService,
                    ParentId = dept.ParetId,
                    Remark = dept.remark,
                    CreateTime = dept.CreateTime ?? DateTime.Now,
                    Children = new List<DepartmentTreeDto>()
                };

                // 如果是顶级科室（ParentId = 0），直接添加到结果列表
                if (dept.ParetId == 0)
                {
                    treeDepartments.Add(treeNode);
                }
                else
                {
                    // 如果是子科室，添加到父科室的Children中
                    if (departmentDict.ContainsKey(dept.ParetId))
                    {
                        var parent = departmentDict[dept.ParetId];
                        // 递归查找父科室在树中的位置
                        var parentInTree = FindParentInTree(treeDepartments, dept.ParetId);
                        if (parentInTree != null)
                        {
                            parentInTree.Children.Add(treeNode);
                        }
                    }
                }
            }

            return treeDepartments;
        }

        /// <summary>
        /// 在树形结构中查找父科室
        /// </summary>
        /// <param name="treeNodes">树形结构节点</param>
        /// <param name="parentId">父科室ID</param>
        /// <returns>父科室节点</returns>
        private DepartmentTreeDto FindParentInTree(List<DepartmentTreeDto> treeNodes, int parentId)
        {
            foreach (var node in treeNodes)
            {
                if (node.Id == parentId)
                {
                    return node;
                }

                // 递归查找子节点
                var foundInChildren = FindParentInTree(node.Children, parentId);
                if (foundInChildren != null)
                {
                    return foundInChildren;
                }
            }

            return null;
        }
    }
} 